//
//  陈日红@2017-6-2 设置-系统设置
//
//

#import "HSysToolsViewController.h"
#import "DBHelper.h"
#import "HLoginSettingViewController.h"

@interface HSysToolsViewController()

@property NSInteger kExecBoxHeight;
@property (nonatomic,strong) UITextView *mySqlTextView;
@property (nonatomic,strong) UILabel *firstSectionView;

@end

@implementation HSysToolsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *execbtn = [[UIBarButtonItem alloc] initWithTitle:@"执行" style:UIBarButtonItemStylePlain target:self action:@selector(didExecButttonClicked:)];
    self.navigationItem.rightBarButtonItem = execbtn;
    
    self.mySqlTextView = [self GetSqlInputView];
    self.firstSectionView = [self GetSectionHeadView:@""];
    [self.view addSubview: self.mySqlTextView];
    [self.view addSubview:self.myTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(instancetype)init{

    self.kExecBoxHeight = 140;
    self.DataSource = [[NSArray alloc]init];
    
    return self;
}

- (IBAction)didExecButttonClicked:(id)sender {
    
    UITextView *txtview = self.mySqlTextView;
    NSString *sql = [txtview.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *msg = @"";
    
    // 执行特定代码，打开打定界面
    if ( [sql isEqualToString:@"#####"]){
        HLoginSettingViewController *vc = [[HLoginSettingViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    

    @try {
        
        [DBHelper.DB open];
        if ([[sql lowercaseString] hasPrefix:@"select"]){
            
            FMResultSet *set = [DBHelper.DB executeQuery:sql];
            NSMutableArray *array = [NSMutableArray array];
            
            
            while ([set next]) {
                
                NSString *row = @"";
                for (int i = 0; i < set.columnCount; i++) {
                    NSString *colName = [set columnNameForIndex:i];
                    NSString *colValue = [set stringForColumnIndex:i];
                    NSString *col = [NSString stringWithFormat:@"%@ : %@", colName,colValue];
                    row =  [row isEqualToString:@""] ?
                    [NSString stringWithFormat:@"%@", col] :
                    [NSString stringWithFormat:@"%@ , %@", row, col] ;
                }
                [array addObject:row];
                
            }
            
            msg = [NSString stringWithFormat: @"共查到%lu条记录", (unsigned long)[array count ]];
            
            self.DataSource = array;
            [self.myTableView reloadData];
            
        }else{
            
            [DBHelper.DB executeStatements:sql];
            msg = @"执行成功";
        }
        
        
        if ([DBHelper.DB hadError]){
            msg = [DBHelper.DB lastErrorMessage];
        }
    }
    @catch (NSException *exception) {
        msg = [NSString stringWithFormat:@"NSException: %@",exception];
    }
    @finally
    {
        [DBHelper.DB close];
    }
    
    self.firstSectionView = [self GetSectionHeadView:msg];
    
    NSLog(@"%@", sql);
    
}

- (UITableView *)myTableView
{
    if (!_myTableView ) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NavBarHeight + self.kExecBoxHeight, ScreenWidth, ScreenHeight - NavBarHeight - self.kExecBoxHeight)];
        _myTableView.dataSource = self;
        _myTableView.delegate = self;
        _myTableView.backgroundColor = UIColor.lightTextColor;
    }
    return _myTableView;
}

#pragma mark SQL 代码输入框

-(UITextView*) GetSqlInputView{
    
    
    UITextView *text = [[UITextView alloc]initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth, self.kExecBoxHeight)];
    text.layer.borderWidth = 1;
    text.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    text.layer.cornerRadius  = 5;
    
    return text;
}

-(UILabel*) GetSectionHeadView:(NSString*) txt{
    
    UILabel * text = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
    text.backgroundColor = RGBA(0xee, 0xee, 0xee, 1);
    
    [text setText: [txt isEqualToString:@"" ] ? @"仅供运维人员使用" : txt];
    return text;
}


#pragma mark UITableView 委托

//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return  nil;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  self.firstSectionView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.DataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cell";
    UITableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    
    cell.textLabel.text = self.DataSource[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *title = self.DataSource[indexPath.row];
    [self alert:title];
    
}

@end

